package com.bjsj.pro.ui;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;


import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.bjsj.pro.base.AAAPresentr;
import com.bjsj.pro.base.HttpBean;
import com.bjsj.pro.base.MVPBaseActivity;
import com.bjsj.pro.base.MyBaseMvpView;
import com.bjsj.pro.base.NullView;
import com.bjsj.pro.base.RetJsonBean;
import com.bjsj.pro.bean.JavaScriptMetod;
import com.bjsj.pro.bean.LoginBean;
import com.bjsj.pro.bean.up_img_2Bean;
import com.bjsj.pro.interfaces.OnJavaScriptMetodCallBack;
import com.bjsj.pro.tools.Configs;
import com.bjsj.pro.tools.ImagerPickerUtils;
import com.bjsj.pro.tools.IntentTools;
import com.bjsj.pro.tools.MyOkgoUtils;
import com.bjsj.pro.tools.PermissionUtils;
import com.bjsj.pro.tools.SeverUrl;
import com.bjsj.pro.tools.getPhotoFromPhotoAlbum;
import com.bjsj.pro.view.X5WebView;
import com.bjsj.pro.R;
import com.bjsj.pro.view.dialogflm.BaseDialog;
import com.bjsj.pro.wxapi.WXLoginCode;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.okgo.model.HttpParams;
import com.nanchen.compresshelper.CompressHelper;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * Created by Nevermore on 2018/1/20.
 * <p>
 * 轮播图商品详情
 */

public class PushTzActivity extends MVPBaseActivity<NullView, AAAPresentr> implements
        NullView
{

    @BindView(R.id.webBannder)
    X5WebView webBannder;
    private String title;
    private String url;
    private String h5Title;
    private int maxImageNum = 1;
    private String upH5Image;
    private IWXAPI mIWXAPI;
    private int up_img_type;
    private boolean isLogin=false;
    private final int GET_TICKET= 100;//获取ticket
    private final int COPY_TEXT=101;//复制文字
    private final int ISLOGIN=102;//是否登录
    private final int GET_USERINFO=103;//获取用户信息
    private final int CALL_PHONE=104;//拨打电话
    private final int CHANGE_TITLE=105;//设置标题
    private final int FILE_DOWLOAD=106;//下载
    private final int IMG_UP=107;//上传
    private final int OPEN_XIANGCE=108;//打开相册
    private final int UP_H5_IMAGE=109;//上传h5
    /**
      * xbs_getTicket  获取ticket
      *      login_ticketback  ticket回调 @params ticket 字符串
      * isLogin   是否登录
      *      login_callback  登录回调 @params isLogin 是否登录 1 or 0
      * xbs_joinLogin  打开登录页面
      * xbs_getUserInfoRequest 获取用户信息
      *       xbs_getUserInfoCallback 用户信息回调 @param {userInfo}
      * xbs_closeWebView  关闭窗口
      * xbs_goBack  返回上一页
      * xbs_changeTitle  设置标题 @params {title}
      * xbs_seeBigPhoto  查看图片 @params {imageArr,index}
      * xbs_copyUrl    复制文字 @params {urlStr}
      * xbs_callPhone   打电话 @param {mobile}
      * xbs_uploadPhoto  上传图片 @params {allowsEdit}
      *      photo_callback 上传回调 @param url 成功的图片路径
      */
    @Override
    protected AAAPresentr createPresenter()
    {
        return new AAAPresentr(this);
    }


    @Override
    protected int setLayoutResId()
    {
        return R.layout.activity_bannder_details;
    }

    @Override
    protected void initData()
    {
        title = getIntent().getStringExtra("title");
        url = getIntent().getStringExtra("url");
        if(url==null){
            url="https://www1.hnbjsj.com/?debug=1";
        }
        showTitleBarLayout(true,"博江小帮手",null,R.drawable.round_login);
        mIWXAPI = WXAPIFactory.createWXAPI(base, Configs.WX_APP_ID, true);
        mIWXAPI.registerApp(Configs.WX_APP_ID);
        EventBus.getDefault().register(this);
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int mDensity = metrics.densityDpi;
        if (mDensity == 240) {
            webBannder.setZoom(WebSettings.ZoomDensity.FAR);
        } else if (mDensity == 160) {
            webBannder.setZoom(WebSettings.ZoomDensity.MEDIUM);
        } else if (mDensity == 120) {
            webBannder.setZoom(WebSettings.ZoomDensity.CLOSE);
        } else if (mDensity == DisplayMetrics.DENSITY_XHIGH) {
            webBannder.setZoom(WebSettings.ZoomDensity.FAR);
        } else if (mDensity == DisplayMetrics.DENSITY_TV) {
            webBannder.setZoom(WebSettings.ZoomDensity.FAR);
        }
        webBannder.getSettings().setJavaScriptEnabled(true);
        webBannder.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webBannder.requestFocus();

        LoginBean userInfo = getUserInfo();
        if(userInfo!=null)
        {
            isLogin=true;
            final CloudPushService pushService = PushServiceFactory.getCloudPushService();
            pushService.bindAccount(userInfo.getData().getUid(), null);
        }

    }

    @Override
    protected void initView()
    {
        Log.d("ffffffffff",url);
        webBannder.loadUrl(url);
        webBannder.addJavascriptInterface(new JavaScriptMetod(new OnJavaScriptMetodCallBack() {
            @Override
            public void xbs_callPhone(String phone) {//打电话
                try {
                    JSONObject json = new JSONObject(phone);
                    String moblie = json.optString("mobile");
                    //  baseHandler.sendEmptyMessageAtTime(GO_USER_PHONE, 1000);
                    Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
                    startActivity(dialIntent);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void xbs_copyUrl(String urlStr) {//复制
                JSONObject json = null;
                try {
                    json = new JSONObject(urlStr);
                    String shareUrlH5 = json.getString("urlStr");
                    if (!TextUtils.isEmpty(shareUrlH5)) {
                        copyString(shareUrlH5);
                    } else {
                        tools.showToast(base, "复制失败,链接内容不存在!");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }



            }

            @Override
            public void xbs_getTicket() {//获取token
                //微信登录
                if (!mIWXAPI.isWXAppInstalled()) {
                    tools.showToast(base, "您还未安装微信客户端");
                    return;
                }
                SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "wechat_login";
                mIWXAPI.sendReq(req);

            }

            @Override
            public void xbs_getUserInfoRequest() {//获取用户信息

            }

            @Override
            public void xbs_changeTitle(String title) {//修改标题
                try {
                    JSONObject json = new JSONObject(title);
                    h5Title = json.optString("title");
                    baseHandler.sendEmptyMessageAtTime(CHANGE_TITLE, 1000);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void xbs_uploadPhoto(String allowsEditjson) {
                Log.d("ssssssssss",allowsEditjson);
                JSONObject json = null;
                try {
                    json = new JSONObject(allowsEditjson);
                    int allowsEdit = json.optInt("allowsEdit", 0);
                    up_img_type=json.optInt("type",0);
                    if (allowsEdit == 1) {
                        ImagerPickerUtils.initImagePickerSingle(true);
                    } else {
                        ImagerPickerUtils.initImagePickerSingle(false);
                    }
                    baseHandler.sendEmptyMessageAtTime(OPEN_XIANGCE, 1000);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void xbs_logout() {
                final CloudPushService pushService = PushServiceFactory.getCloudPushService();
                pushService.unbindAccount(null);
                tools.saveObject(base, Configs.SAVE_LOGIN_KEY, Configs.SAVE_LOGIN_SP_NAME, null);
                tools.showToast(base,"退出登陆");
            }

            @Override
            public void xbs_orderPay(String apppayrequest) {

            }

            @Override
            public void xbs_startRecord() {

            }

            @Override
            public void xbs_closeRecord() {

            }

            @Override
            public void xbs_stopRecord(String json) {

            }



        }),"Android");


        webBannder.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {

                tools.showToast(base,message);
                result.confirm();

                return true;
            }
        });

    }



    private static long exitTime = 0;

    /*public void onBackPressed() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast toast = Toast.makeText(base, "再按一次退出！", Toast.LENGTH_SHORT);
            toast.show();
            exitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }
    }*/


    /*public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) ) {
            if (webBannder.canGoBack())
            {
                webBannder.goBack(); //goBack()表示返回WebView的上一页面
                return true;
            }else
            {
                if ((System.currentTimeMillis() - exitTime) > 2000) {
                    Toast toast = Toast.makeText(base, "再按一次退出！", Toast.LENGTH_SHORT);
                    toast.show();
                    exitTime = System.currentTimeMillis();
                } else {
                    finish();
                    System.exit(0);
                    return true;
                }

            }

        }
        return false;
    }*/


    @Subscribe(threadMode = ThreadMode.MainThread)
    public void messageEventBus(WXLoginCode event) {
        tools.logD("===========messageEventBus event：" + event.getRespCode());
        if (event.getGetType().equals("303774") && !TextUtils.isEmpty(event.getRespCode())) {
            //微信登陆成功后返回code,然后通过code去获取用户个人资料
            // getWXUserInfo(base, event.getRespCode());
            startLogin(event.getRespCode());
        } else {
            tools.showToast(base, "获取微信授权信息失败!");
        }

    }


    private void copyString(String copyString) {
        if (!TextUtils.isEmpty(copyString)) {
            ClipboardManager clipboardManager = (ClipboardManager) base.getSystemService(Context.CLIPBOARD_SERVICE);
            clipboardManager.setPrimaryClip(ClipData.newPlainText(null, copyString));
            tools.showToast(base, "复制成功!");
        }
    }


    public void handlerMessage(Message msg)
    {
        // super.handlerMessage(msg);
        switch (msg.what)
        {
            case CALL_PHONE:
                tools.showToast(base, "成功");
                break;
            case COPY_TEXT:
                tools.showToast(base, "app复制成功");
                break;
            case CHANGE_TITLE:
                if (!TextUtils.isEmpty(h5Title)) {
                    mTitleBarLayout.setTitle(h5Title.toString().trim());
                }
                break;
            case OPEN_XIANGCE:
                //打开相册
                if (!XXPermissions.hasPermission(base, Permission.Group.STORAGE)) {
                    PermissionUtils.getSDtorPermisstion(base, new PermissionUtils.Permissions() {
                        @Override
                        public void getPermission(boolean isAll) {
                            if (isAll) {
//                              所有获取权限成功
                                IntentTools.gotoPick(base, maxImageNum);
                            } else {
//                  获取权限成功，部分权限未正常授予
                            }
                        }
                    });
                } else {
                    IntentTools.gotoPick(base, maxImageNum);
                }
                break;
            case UP_H5_IMAGE:
                //照片传给h5
                Log.d("sssssssssssss",upH5Image);
                //webBannder.loadUrl("javascript: photo_callback(\""+upH5Image+"\")");
                webBannder.loadUrl("javascript: photo_callback(\'"+upH5Image+"\')");
                break;
        }
    }

    ArrayList<ImageItem> images = null;

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == Configs.REQUEST_ALBUM_OK) {

            String photoPath = getPhotoFromPhotoAlbum.getRealPathFromUri(this, data.getData());
            //  uploadImage(photoPath);
            tools.logD("=======相册:" + photoPath);
        }


        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == Configs.REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    //  adapter.setImages(selImageList);
                    //   tools.logD("==========selImageList" + picList.size());
                    tools.logD("==========images" + images.size());
                    // picList.clear();
                    for (int i = 0; i < images.size(); i++) {
                        if(up_img_type==1) {
                            uploadImage(images.get(i).path);
                        }else {
                            uploadImage_2(images.get(i).path);
                        }
                  /*      picList.add(images.get(i).path);
                        mImageUrlrAdapter.setImages(picList);*/
                    }

                }
            } else if (data != null && requestCode == Configs.REQUEST_CODE_PHONE) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    //  tools.logD("==========REQUEST_CODE_SELECT selImageList" + picList.size());
                    tools.logD("==========REQUEST_CODE_SELECT images" + images.size());
                    // adapter.setImages(selImageList);
                    for (int i = 0; i < images.size(); i++) {
                        if(up_img_type==1){
                            uploadImage(images.get(i).path);
                        }else {
                            uploadImage_2(images.get(i).path);
                        }

                        //  picList.add(images.get(i).path);
                        //   mImageUrlrAdapter.setImages(picList);
                    }
                }
            }

        }
    }


    public void uploadImage(String path) {
        File newFile = CompressHelper.getDefault(base)
                .compressToFile(new File(path));

        HttpBean mHttpBean = new HttpBean(getSupportFragmentManager());
        mHttpBean.setHttpGetType(Configs.OKGO_POST);
        mHttpBean.setHttpurl(SeverUrl.IMG_UP);
        mHttpBean.setGetType(Configs.OKGO_GET_TYPE_PROGRESS);
        HttpParams params = new HttpParams();
        params.put("file", newFile);
        params.put("isApp",1);
        mHttpBean.setToken(getToken());
        mHttpBean.setHttpParams(params);
        MyOkgoUtils.newInstance().startHttpRequest(base, mHttpBean, up_img_2Bean.class, new MyBaseMvpView<up_img_2Bean>() {
            @Override
            public void onSuccessShowData(up_img_2Bean data) {
                super.onSuccessShowData(data);
                Gson gson=new Gson();
                String json=gson.toJson(data);
                if (!TextUtils.isEmpty(data.getData().getTurl())) {
                    upH5Image = json;
                    baseHandler.sendEmptyMessageAtTime(UP_H5_IMAGE, 1000);
                }

            }

        });

    }


    public void uploadImage_2(String path) {
        File newFile = CompressHelper.getDefault(base)
                .compressToFile(new File(path));

        HttpBean mHttpBean = new HttpBean(getSupportFragmentManager());
        mHttpBean.setHttpGetType(Configs.OKGO_POST);
        mHttpBean.setHttpurl(SeverUrl.IMG_UP_2);
        mHttpBean.setGetType(Configs.OKGO_GET_TYPE_PROGRESS);
        HttpParams params = new HttpParams();
        params.put("Filedata", newFile);
        params.put("name",newFile.getName());
        params.put("isApp",1);
        mHttpBean.setToken(getToken());
        mHttpBean.setHttpParams(params);
        MyOkgoUtils.newInstance().startHttpRequest(base, mHttpBean, up_img_2Bean.class, new MyBaseMvpView<up_img_2Bean>() {
            @Override
            public void onSuccessShowData(up_img_2Bean data) {
                super.onSuccessShowData(data);
                Gson gson=new Gson();
                String json=gson.toJson(data);
                if (!TextUtils.isEmpty(data.getData().getTurl())) {
                    upH5Image = json;
                    baseHandler.sendEmptyMessageAtTime(UP_H5_IMAGE, 1000);
                }


            }

        });

    }


    public void startLogin(String code) {

        HttpParams params = new HttpParams();
        params.put("code", code);
        params.put("isApp",1);
        /* params.put("unionid", mWXUserInfo.getUnionid());
        params.put("sex", mWXUserInfo.getSex());
        params.put("provice", mWXUserInfo.getProvince());
        params.put("city", mWXUserInfo.getCity());*/
        HttpBean mHttp = new HttpBean(getSupportFragmentManager());
        mHttp.setHttpGetType(Configs.OKGO_GET);
        mHttp.setGetType(Configs.OKGO_GET_TYPE_PROGRESS);
        mHttp.setHttpurl(SeverUrl.LOGIN);//WX_LOGIN
        mHttp.setHttpParams(params);

        MyOkgoUtils.newInstance().startHttpRequest(base, mHttp, LoginBean.class, new MyBaseMvpView<LoginBean>() {
            @Override
            public void onSuccessShowData(LoginBean data) {
                super.onSuccessShowData(data);
                tools.saveObject(base, Configs.SAVE_LOGIN_KEY, Configs.SAVE_LOGIN_SP_NAME, data);
                final CloudPushService pushService = PushServiceFactory.getCloudPushService();
                pushService.bindAccount(data.getData().getUid(), null);
                setDevice();
                webBannder.loadUrl(data.getData().getToUrl());
            }
        });
    }


    public void setDevice() {

        HttpParams params = new HttpParams();
        params.put("system", "Android");
        params.put("versions",getLocalVersion(base));
        /* params.put("unionid", mWXUserInfo.getUnionid());
        params.put("sex", mWXUserInfo.getSex());
        params.put("provice", mWXUserInfo.getProvince());
        params.put("city", mWXUserInfo.getCity());*/
        HttpBean mHttp = new HttpBean(getSupportFragmentManager());
        mHttp.setHttpGetType(Configs.OKGO_GET);
        mHttp.setGetType(Configs.OKGO_GET_TYPE_PROGRESS);
        mHttp.setHttpurl(SeverUrl.LOGIN);//WX_LOGIN
        mHttp.setToken(getToken());
        mHttp.setHttpParams(params);

        MyOkgoUtils.newInstance().startHttpRequest(base, mHttp,RetJsonBean.class, new MyBaseMvpView<RetJsonBean>() {
            @Override
            public void onSuccessShowData(RetJsonBean data) {
                super.onSuccessShowData(data);

            }
        });
    }




    @Override
    public void onDestroy()
    {
        super.onDestroy();
        if (this.webBannder!= null) {
            webBannder.destroy();
        }
    }
}
